import { forEach } from 'lodash-es';
/* eslint-disable @typescript-eslint/indent */
import { SetupContext, ref } from "vue";
import { FieldConfig, Condition } from "../types";
import { ConditionProps } from "../condition.props";
import { UseFieldConfig } from "./types";
import { EditorConfig } from "../../../dynamic-form";
import { useConditionValue } from "./use-condition-value";

export function useFieldConfig(props: ConditionProps, context: SetupContext): UseFieldConfig {

    const fields = ref<FieldConfig[]>(props.fields);
    const fieldConditions = ref<FieldConfig[]>([]);
    const fieldMap = new Map<string, FieldConfig>();
    const { createConditionValue } = useConditionValue();

    function getSingleControlType(fieldConfig: FieldConfig): EditorConfig {
        const controlType = fieldConfig.editor ? fieldConfig.editor.type : 'input-group';
        switch (controlType) {
            case 'date-range':
                fieldConfig.editor.type = 'date-picker';
                break;
            case 'datetime-range':
                fieldConfig.editor.type = 'datetime-picker';
                break;
            case 'number-range':
                fieldConfig.editor.type = 'number-spinner';
                break;
        }
        return fieldConfig.editor;
    }

    function convertToSingleControl(configs: FieldConfig[]): FieldConfig[] {
        const convertedFieldConfigs = configs.map((fieldConfig: FieldConfig) => Object.assign({}, fieldConfig))
            .map((fieldConfig: FieldConfig) => {
                fieldConfig.editor = getSingleControlType(fieldConfig);
                return fieldConfig;
            });
        return convertedFieldConfigs;
    }

    function loadFieldConfigs(useRangeEditor = true) {
        fields.value.reduce((result: Map<string, FieldConfig>, field: FieldConfig) => {
            if (!useRangeEditor) {
                field.editor = getSingleControlType(field);
            }
            result.set(field.labelCode, field);
            return result;
        }, fieldMap);
    }

    function initialConditionValue(conditions: Condition[]) {
        conditions.forEach((fieldCondition: Condition) => {
            if (fieldCondition && (typeof fieldCondition.value !== 'object')) {
                const selectedField = fieldMap.get(fieldCondition.fieldCode) as FieldConfig;
                fieldCondition.value = createConditionValue(selectedField.editor.type);
            }
        });
        return conditions;
    }

    return { convertToSingleControl, fields, fieldMap, fieldConditions, loadFieldConfigs, initialConditionValue };
}
